<template>
  <el-select
    :disabled="disabled"
    v-model="myModel"
    :multiple="multi"
    filterable
    remote
    reserve-keyword
    :placeholder="placeholder"
    :remote-method="remoteMethod"
    :loading="loading" size="mini"
     style="width:200px">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>

<script>
  export default {
    name: 'UserSelector',
    props:{
      model:{
        type: Array,
        default: []
      },
      select:{
        type:Function,
      },
      placeholder:{
        type:String,
        required:true,
        default: '请选择'
      },
      multi:{
        type:Boolean,
        default:true
      },
      disabled:{
        type:Boolean,
        default:false
      }
    },
    data(){
      return{
        options: [],
        list: [],
        loading: false,
        states:[],
        myModel: this.model,
      }
    },
    mounted() {
      this.loadSource();
    },
    watch:{
      model(val){
        this.myModel = val;
      },
      myModel(val){
        this.setVal(val);
      }
    },
    methods: {
      remoteMethod: function(query) {
        if (query !== '') {
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
            this.options = this.list.filter(item => {
              return item.label.toLowerCase()
                .indexOf(query.toLowerCase()) > -1;
            });
          }, 200);
        } else {
          this.options = [];
        }
      },
      loadSource: function() {
        this.$api.post(  '/wf/user/all').then(res => {
          if (res != null) {
            this.list = res;
            this.setVal(this.model);
          }
        });
      },
      setVal:function(val){
        let k = [];
        k = this.list.filter((item)=>{
          //筛选出匹配数据，是对应数据的整个对象
          let flag = false;
          for(let i = 0 ; i < val.length ; i ++){
            if(val[i] === item.value){
              flag = true;
              break;
            }
          }
          return flag;
        });
        this.options = k;
        this.$emit("select",k);

      }
    }
  }
</script>

<style scoped>

</style>
